<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>基于VFH描述自聚类识别与位姿估计 | 荒岛</title><meta name="author" content="Fi9zero"><meta name="copyright" content="Fi9zero"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="build_tree.cppbuild_tree.cpp 是一个用于为点云识别系统构建训练数据和搜索索引的程序。它从指定目录中加载所有VFH特征文件，将它们组织成训练数据集，并构建一个高效的FLANN搜索索引。 1. 核心功能概述 加载VFH模型：从命令行参数指定的目录中，递归地搜索并加载所有.pcd格式的VFH特征文件。 构建训练数据集：将所有加载的VFH特征向量（308维）组织成一个矩阵，并将">
<meta property="og:type" content="article">
<meta property="og:title" content="基于VFH描述自聚类识别与位姿估计">
<meta property="og:url" content="https://ckyfi9zero.github.io/2025/08/04/2025-08-04-%E5%9F%BA%E4%BA%8EVFH%E6%8F%8F%E8%BF%B0%E8%87%AA%E8%81%9A%E7%B1%BB%E8%AF%86%E5%88%AB%E4%B8%8E%E4%BD%8D%E5%A7%BF%E4%BC%B0%E8%AE%A1/index.html">
<meta property="og:site_name" content="荒岛">
<meta property="og:description" content="build_tree.cppbuild_tree.cpp 是一个用于为点云识别系统构建训练数据和搜索索引的程序。它从指定目录中加载所有VFH特征文件，将它们组织成训练数据集，并构建一个高效的FLANN搜索索引。 1. 核心功能概述 加载VFH模型：从命令行参数指定的目录中，递归地搜索并加载所有.pcd格式的VFH特征文件。 构建训练数据集：将所有加载的VFH特征向量（308维）组织成一个矩阵，并将">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://ckyfi9zero.github.io/image/avatar.jpg">
<meta property="article:published_time" content="2025-08-04T11:36:25.000Z">
<meta property="article:modified_time" content="2025-08-04T11:43:47.609Z">
<meta property="article:author" content="Fi9zero">
<meta property="article:tag" content="c++">
<meta property="article:tag" content="PCL">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://ckyfi9zero.github.io/image/avatar.jpg"><script type="application/ld+json">{
  "@context": "https://schema.org",
  "@type": "BlogPosting",
  "headline": "基于VFH描述自聚类识别与位姿估计",
  "url": "https://ckyfi9zero.github.io/2025/08/04/2025-08-04-%E5%9F%BA%E4%BA%8EVFH%E6%8F%8F%E8%BF%B0%E8%87%AA%E8%81%9A%E7%B1%BB%E8%AF%86%E5%88%AB%E4%B8%8E%E4%BD%8D%E5%A7%BF%E4%BC%B0%E8%AE%A1/",
  "image": "https://ckyfi9zero.github.io/image/avatar.jpg",
  "datePublished": "2025-08-04T11:36:25.000Z",
  "dateModified": "2025-08-04T11:43:47.609Z",
  "author": [
    {
      "@type": "Person",
      "name": "Fi9zero",
      "url": "https://ckyfi9zero.github.io"
    }
  ]
}</script><link rel="shortcut icon" href="/image/favicon.ico"><link rel="canonical" href="https://ckyfi9zero.github.io/2025/08/04/2025-08-04-%E5%9F%BA%E4%BA%8EVFH%E6%8F%8F%E8%BF%B0%E8%87%AA%E8%81%9A%E7%B1%BB%E8%AF%86%E5%88%AB%E4%B8%8E%E4%BD%8D%E5%A7%BF%E4%BC%B0%E8%AE%A1/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css"><script>
    (() => {
      
    const saveToLocal = {
      set: (key, value, ttl) => {
        if (!ttl) return
        const expiry = Date.now() + ttl * 86400000
        localStorage.setItem(key, JSON.stringify({ value, expiry }))
      },
      get: key => {
        const itemStr = localStorage.getItem(key)
        if (!itemStr) return undefined
        const { value, expiry } = JSON.parse(itemStr)
        if (Date.now() > expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return value
      }
    }

    window.btf = {
      saveToLocal,
      getScript: (url, attr = {}) => new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = url
        script.async = true
        Object.entries(attr).forEach(([key, val]) => script.setAttribute(key, val))
        script.onload = script.onreadystatechange = () => {
          if (!script.readyState || /loaded|complete/.test(script.readyState)) resolve()
        }
        script.onerror = reject
        document.head.appendChild(script)
      }),
      getCSS: (url, id) => new Promise((resolve, reject) => {
        const link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = url
        if (id) link.id = id
        link.onload = link.onreadystatechange = () => {
          if (!link.readyState || /loaded|complete/.test(link.readyState)) resolve()
        }
        link.onerror = reject
        document.head.appendChild(link)
      }),
      addGlobalFn: (key, fn, name = false, parent = window) => {
        if (!false && key.startsWith('pjax')) return
        const globalFn = parent.globalFn || {}
        globalFn[key] = globalFn[key] || {}
        globalFn[key][name || Object.keys(globalFn[key]).length] = fn
        parent.globalFn = globalFn
      }
    }
  
      
      const activateDarkMode = () => {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      const activateLightMode = () => {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }

      btf.activateDarkMode = activateDarkMode
      btf.activateLightMode = activateLightMode

      const theme = saveToLocal.get('theme')
    
          theme === 'dark' ? activateDarkMode() : theme === 'light' ? activateLightMode() : null
        
      
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        document.documentElement.classList.toggle('hide-aside', asideStatus === 'hide')
      }
    
      
    const detectApple = () => {
      if (/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)) {
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
  
    })()
  </script><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":true,"top_n_per_article":1,"unescape":false,"languages":{"hits_empty":"未找到符合您查询的内容：${query}","hits_stats":"共找到 ${hits} 篇文章"}},
  translate: undefined,
  highlight: {"plugin":"highlight.js","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false,"highlightFullpage":false,"highlightMacStyle":true},
  copy: {
    success: '复制成功',
    error: '复制失败',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'null',
  Snackbar: undefined,
  infinitegrid: {
    js: 'https://cdn.jsdelivr.net/npm/@egjs/infinitegrid/dist/infinitegrid.min.js',
    buttonText: '加载更多'
  },
  isPhotoFigcaption: false,
  islazyloadPlugin: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '基于VFH描述自聚类识别与位姿估计',
  isHighlightShrink: false,
  isToc: true,
  pageType: 'post'
}</script><link rel="stylesheet" href="/css/custom.css"><link rel="stylesheet" href="/css/pig.css"><link rel="stylesheet" href="https://npm.elemecdn.com/ethan4116-blog/lib/css/plane_v2.css"><meta name="generator" content="Hexo 7.3.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img text-center"><img src="/image/avatar.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data text-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">54</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">15</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">8</div></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/booklist/"><i class="fa-fw fas fa-book"></i><span> 书单</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 链接</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url(/image/per%20page.jpg);"><nav id="nav"><span id="blog-info"><a class="nav-site-title" href="/"><span class="site-name">荒岛</span></a><a class="nav-page-title" href="/"><span class="site-name">基于VFH描述自聚类识别与位姿估计</span><span class="site-name"><i class="fa-solid fa-circle-arrow-left"></i><span>  返回首页</span></span></a></span><div id="menus"><div id="search-button"><span class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></span></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/booklist/"><i class="fa-fw fas fa-book"></i><span> 书单</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 链接</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><span class="site-page"><i class="fas fa-bars fa-fw"></i></span></div></div></nav><div id="post-info"><h1 class="post-title">基于VFH描述自聚类识别与位姿估计</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2025-08-04T11:36:25.000Z" title="发表于 2025-08-04 19:36:25">2025-08-04</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2025-08-04T11:43:47.609Z" title="更新于 2025-08-04 19:43:47">2025-08-04</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/PCL/">PCL</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title=""><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">浏览量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="container post-content" id="article-container"><h1 id="build-tree-cpp"><a href="#build-tree-cpp" class="headerlink" title="build_tree.cpp"></a>build_tree.cpp</h1><p><code>build_tree.cpp</code> 是一个用于为点云识别系统构建训练数据和搜索索引的程序。它从指定目录中加载所有VFH特征文件，将它们组织成训练数据集，并构建一个高效的FLANN搜索索引。</p>
<h2 id="1-核心功能概述"><a href="#1-核心功能概述" class="headerlink" title="1. 核心功能概述"></a>1. 核心功能概述</h2><ol>
<li><strong>加载VFH模型</strong>：从命令行参数指定的目录中，递归地搜索并加载所有<code>.pcd</code>格式的VFH特征文件。</li>
<li><strong>构建训练数据集</strong>：将所有加载的VFH特征向量（308维）组织成一个矩阵，并将其与文件路径列表一起保存到磁盘。</li>
<li><strong>创建搜索索引</strong>：使用FLANN库为特征矩阵构建一个KD-Tree（或线性索引）搜索索引，以便后续程序能快速进行最近邻搜索。</li>
</ol>
<h2 id="2-重要数据结构"><a href="#2-重要数据结构" class="headerlink" title="2. 重要数据结构"></a>2. 重要数据结构</h2><ul>
<li><strong><code>vfh_model</code></strong>: <code>std::pair&lt;std::string, std::vector&lt;float&gt;&gt;</code>。这是一个自定义类型，用于存储一个VFH模型。<ul>
<li><code>first</code>: <code>std::string</code>，存储该VFH特征文件的完整路径。</li>
<li><code>second</code>: <code>std::vector&lt;float&gt;</code>，存储308维的VFH特征向量。</li>
</ul>
</li>
<li><strong><code>flann::Matrix&lt;float&gt;</code></strong>: FLANN库中的矩阵类型，用于在内存中存储所有VFH特征向量，形成一个<code>N x 308</code>的矩阵（N为模型总数），这是构建索引的基础。</li>
</ul>
<h2 id="3-关键函数"><a href="#3-关键函数" class="headerlink" title="3. 关键函数"></a>3. 关键函数</h2><h3 id="loadHist-const-boost-filesystem-path-path-vfh-model-vfh"><a href="#loadHist-const-boost-filesystem-path-path-vfh-model-vfh" class="headerlink" title="loadHist(const boost::filesystem::path &amp;path, vfh_model &amp;vfh)"></a><code>loadHist(const boost::filesystem::path &amp;path, vfh_model &amp;vfh)</code></h3><ul>
<li><strong>功能</strong>：从一个<code>.pcd</code>文件中加载VFH特征。</li>
<li><strong>步骤</strong>：<ol>
<li>通过<code>readHeader</code>检查文件是否包含”vfh”字段且为1x1点云。</li>
<li>使用<code>loadPCDFile</code>加载完整的PCD文件。</li>
<li>将<code>pcl::VFHSignature308</code>点的<code>histogram</code>数组复制到<code>vfh</code>参数的<code>second</code>向量中。</li>
<li>将文件路径保存到<code>vfh</code>参数的<code>first</code>成员中。</li>
</ol>
</li>
<li><strong>返回值</strong>：<code>true</code>表示加载成功，<code>false</code>表示失败。</li>
</ul>
<h3 id="loadFeatureModels-const-boost-filesystem-path-base-dir-std-vector-models"><a href="#loadFeatureModels-const-boost-filesystem-path-base-dir-std-vector-models" class="headerlink" title="loadFeatureModels(const boost::filesystem::path &amp;base_dir, ... , std::vector&lt;vfh_model&gt; &amp;models)"></a><code>loadFeatureModels(const boost::filesystem::path &amp;base_dir, ... , std::vector&lt;vfh_model&gt; &amp;models)</code></h3><ul>
<li><strong>功能</strong>：递归地加载一个目录及其所有子目录中的VFH模型。</li>
<li><strong>步骤</strong>：<ol>
<li>遍历<code>base_dir</code>下的所有条目。</li>
<li>如果遇到子目录，递归调用自身。</li>
<li>如果遇到扩展名为<code>.pcd</code>的文件，调用<code>loadHist</code>尝试加载，成功则加入<code>models</code>向量。</li>
</ol>
</li>
<li><strong>特点</strong>：实现了深度优先的目录遍历。</li>
</ul>
<h3 id="main"><a href="#main" class="headerlink" title="main(...)"></a><code>main(...)</code></h3><ul>
<li><strong>功能</strong>：程序主入口，协调数据加载、格式转换、文件保存和索引构建。</li>
<li><strong>关键步骤</strong>：<ol>
<li><strong>参数检查</strong>：确保提供了模型目录。</li>
<li><strong>加载模型</strong>：调用<code>loadFeatureModels</code>填充<code>models</code>向量。</li>
<li><strong>数据转换</strong>：将<code>models</code>向量中的特征向量复制到<code>flann::Matrix&lt;float&gt; data</code>中。</li>
<li><strong>保存训练数据</strong>：<ul>
<li><code>flann::save_to_file(data, &quot;training_data.h5&quot;, &quot;training_data&quot;)</code>: 将特征矩阵保存为HDF5文件。</li>
<li><code>std::ofstream</code> + <code>models[i].first</code>: 将文件路径列表保存为纯文本<code>.list</code>文件。</li>
</ul>
</li>
<li><strong>构建并保存索引</strong>：<ul>
<li>创建<code>flann::Index</code>对象。</li>
<li>调用<code>index.buildIndex()</code>构建索引。</li>
<li>调用<code>index.save(&quot;kdtree.idx&quot;)</code>将索引保存到文件。</li>
</ul>
</li>
<li><strong>内存清理</strong>：<code>delete[] data.ptr()</code>释放动态分配的内存。</li>
</ol>
</li>
</ul>
<h2 id="4-生成的文件"><a href="#4-生成的文件" class="headerlink" title="4. 生成的文件"></a>4. 生成的文件</h2><p>该程序成功运行后，会在当前目录生成三个关键文件，供<code>nearest_neighbors</code>程序使用：</p>
<ul>
<li><code>training_data.h5</code>: 包含所有VFH特征向量的HDF5二进制文件。</li>
<li><code>training_data.list</code>: 包含所有VFH文件路径的文本文件。</li>
<li><code>kdtree.idx</code>: 由FLANN构建的KD-Tree搜索索引文件。</li>
</ul>
<h2 id="5-注意事项"><a href="#5-注意事项" class="headerlink" title="5. 注意事项"></a>5. 注意事项</h2><ul>
<li><strong>FLANN距离度量</strong>：代码中使用了<code>flann::ChiSquareDistance&lt;float&gt;</code>，这适用于直方图数据的卡方距离计算。</li>
<li><strong>索引类型</strong>：代码中创建索引时使用了<code>flann::LinearIndexParams()</code>，这会创建一个线性搜索索引，效率很低。正确的做法是使用<code>flann::KDTreeIndexParams(4)</code>或<code>flann::AutotunedIndexParams()</code>。</li>
<li><strong>依赖库</strong>：此程序依赖PCL、Boost和FLANN库，并且由于使用了HDF5，编译时必须链接<code>libhdf5-dev</code>。</li>
</ul>
<h2 id="代码实现"><a href="#代码实现" class="headerlink" title="代码实现"></a>代码实现</h2><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pcl/point_types.h&gt;</span>                     <span class="comment">// PCL点类型定义，如 pcl::PointXYZ, pcl::VFHSignature308</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pcl/point_cloud.h&gt;</span>                     <span class="comment">// PCL点云数据结构 pcl::PointCloud</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pcl/console/parse.h&gt;</span>                   <span class="comment">// PCL命令行解析工具</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pcl/console/print.h&gt;</span>                   <span class="comment">// PCL控制台输出工具，如高亮、打印</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pcl/io/pcd_io.h&gt;</span>                       <span class="comment">// PCL的PCD文件读写功能</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;boost/filesystem.hpp&gt;</span>                  <span class="comment">// Boost文件系统库，用于遍历目录和文件</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;flann/flann.h&gt;</span>                         <span class="comment">// FLANN库主头文件，用于最近邻搜索</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;flann/io/hdf5.h&gt;</span>                       <span class="comment">// FLANN的HDF5文件读写功能</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;fstream&gt;</span>                               <span class="comment">// C++标准文件流，用于写入文本文件</span></span></span><br><span class="line"></span><br><span class="line"><span class="keyword">typedef</span> std::pair&lt;std::string, std::vector&lt;<span class="type">float</span>&gt; &gt; vfh_model; <span class="comment">// 定义一个别名，表示一个VFH模型，包含文件路径和308维特征向量</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/** \brief Loads an n-D histogram file as a VFH signature</span></span><br><span class="line"><span class="comment">  * \param path the input file name</span></span><br><span class="line"><span class="comment">  * \param vfh the resultant VFH model</span></span><br><span class="line"><span class="comment">  */</span></span><br><span class="line"><span class="function"><span class="type">bool</span></span></span><br><span class="line"><span class="function"><span class="title">loadHist</span> <span class="params">(<span class="type">const</span> boost::filesystem::path &amp;path, vfh_model &amp;vfh)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  <span class="type">int</span> vfh_idx;</span><br><span class="line">  <span class="comment">// Load the file as a PCD</span></span><br><span class="line">  <span class="keyword">try</span></span><br><span class="line">  &#123;</span><br><span class="line">    pcl::PCLPointCloud2 cloud;                   <span class="comment">// 用于存储PCD文件头信息的通用点云数据结构</span></span><br><span class="line">    <span class="type">int</span> version;                                 <span class="comment">// PCD文件版本</span></span><br><span class="line">    Eigen::Vector4f origin;                      <span class="comment">// PCD文件的原点</span></span><br><span class="line">    Eigen::Quaternionf orientation;              <span class="comment">// PCD文件的朝向</span></span><br><span class="line">    pcl::PCDReader r;                            <span class="comment">// PCD文件读取器</span></span><br><span class="line">    <span class="type">int</span> type; <span class="type">unsigned</span> <span class="type">int</span> idx;                  <span class="comment">// 用于存储PCD文件的类型和索引</span></span><br><span class="line">    r.<span class="built_in">readHeader</span> (path.<span class="built_in">string</span> (), cloud, origin, orientation, version, type, idx); <span class="comment">// 只读取PCD文件头，不加载数据</span></span><br><span class="line"></span><br><span class="line">    vfh_idx = pcl::<span class="built_in">getFieldIndex</span> (cloud, <span class="string">&quot;vfh&quot;</span>); <span class="comment">// 在点云字段中查找名为 &quot;vfh&quot; 的字段索引</span></span><br><span class="line">    <span class="keyword">if</span> (vfh_idx == <span class="number">-1</span>)                           <span class="comment">// 如果没有找到 &quot;vfh&quot; 字段</span></span><br><span class="line">      <span class="keyword">return</span> (<span class="literal">false</span>);                            <span class="comment">// 返回false，加载失败</span></span><br><span class="line">    <span class="keyword">if</span> ((<span class="type">int</span>)cloud.width * cloud.height != <span class="number">1</span>)    <span class="comment">// VFH特征文件应为1x1的点云（单个点）</span></span><br><span class="line">      <span class="keyword">return</span> (<span class="literal">false</span>);                            <span class="comment">// 如果不是，返回false</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="built_in">catch</span> (pcl::InvalidConversionException e)      <span class="comment">// 捕获PCD读取异常</span></span><br><span class="line">  &#123;</span><br><span class="line">    <span class="keyword">return</span> (<span class="literal">false</span>);                              <span class="comment">// 发生异常，返回false</span></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// Treat the VFH signature as a single Point Cloud</span></span><br><span class="line">  pcl::PointCloud &lt;pcl::VFHSignature308&gt; point;  <span class="comment">// 声明一个VFH特征点云，它只包含一个点，该点有308维直方图</span></span><br><span class="line">  pcl::io::<span class="built_in">loadPCDFile</span> (path.<span class="built_in">string</span> (), point);  <span class="comment">// 加载完整的PCD文件到VFH点云中</span></span><br><span class="line">  vfh.second.<span class="built_in">resize</span> (<span class="number">308</span>);                       <span class="comment">// 为vfh模型的特征向量分配308个float的空间</span></span><br><span class="line"></span><br><span class="line">  std::vector &lt;pcl::PCLPointField&gt; fields;       <span class="comment">// 存储点云字段信息的向量</span></span><br><span class="line">  pcl::<span class="built_in">getFieldIndex</span> (point, <span class="string">&quot;vfh&quot;</span>, fields);     <span class="comment">// 获取 &quot;vfh&quot; 字段的详细信息</span></span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span> (<span class="type">size_t</span> i = <span class="number">0</span>; i &lt; fields[vfh_idx].count; ++i) <span class="comment">// 遍历 &quot;vfh&quot; 字段的所有值（308个）</span></span><br><span class="line">  &#123;</span><br><span class="line">    vfh.second[i] = point.points[<span class="number">0</span>].histogram[i]; <span class="comment">// 将加载的VFH特征值复制到vfh模型中</span></span><br><span class="line">  &#125;</span><br><span class="line">  vfh.first = path.<span class="built_in">string</span> ();                    <span class="comment">// 将文件路径保存到vfh模型中</span></span><br><span class="line">  <span class="keyword">return</span> (<span class="literal">true</span>);                                 <span class="comment">// 加载成功，返回true</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/** \brief Load a set of VFH features that will act as the model (training data)</span></span><br><span class="line"><span class="comment">  * \param argc the number of arguments (pass from main ())</span></span><br><span class="line"><span class="comment">  * \param argv the actual command line arguments (pass from main ())</span></span><br><span class="line"><span class="comment">  * \param extension the file extension containing the VFH features</span></span><br><span class="line"><span class="comment">  * \param models the resultant vector of histogram models</span></span><br><span class="line"><span class="comment">  */</span></span><br><span class="line"><span class="function"><span class="type">void</span></span></span><br><span class="line"><span class="function"><span class="title">loadFeatureModels</span> <span class="params">(<span class="type">const</span> boost::filesystem::path &amp;base_dir, <span class="type">const</span> std::string &amp;extension, </span></span></span><br><span class="line"><span class="params"><span class="function">                   std::vector&lt;vfh_model&gt; &amp;models)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (!boost::filesystem::<span class="built_in">exists</span> (base_dir) &amp;&amp; !boost::filesystem::<span class="built_in">is_directory</span> (base_dir)) <span class="comment">// 检查基础目录是否存在且为目录</span></span><br><span class="line">    <span class="keyword">return</span>;                                      <span class="comment">// 如果不存在或不是目录，直接返回</span></span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span> (boost::filesystem::directory_iterator <span class="built_in">it</span> (base_dir); it != boost::filesystem::<span class="built_in">directory_iterator</span> (); ++it) <span class="comment">// 遍历目录下的所有条目</span></span><br><span class="line">  &#123;</span><br><span class="line">    <span class="keyword">if</span> (boost::filesystem::<span class="built_in">is_directory</span> (it-&gt;<span class="built_in">status</span> ())) <span class="comment">// 如果当前条目是子目录</span></span><br><span class="line">    &#123;</span><br><span class="line">      std::stringstream ss;                      <span class="comment">// 创建字符串流</span></span><br><span class="line">      ss &lt;&lt; it-&gt;<span class="built_in">path</span> ();                         <span class="comment">// 将子目录路径转换为字符串</span></span><br><span class="line">      pcl::console::<span class="built_in">print_highlight</span> (<span class="string">&quot;Loading %s (%lu models loaded so far).\n&quot;</span>, ss.<span class="built_in">str</span> ().<span class="built_in">c_str</span> (), (<span class="type">unsigned</span> <span class="type">long</span>)models.<span class="built_in">size</span> ()); <span class="comment">// 打印正在加载的目录和已加载模型数量</span></span><br><span class="line">      <span class="built_in">loadFeatureModels</span> (it-&gt;<span class="built_in">path</span> (), extension, models); <span class="comment">// 递归调用自身，加载子目录中的模型</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (boost::filesystem::<span class="built_in">is_regular_file</span> (it-&gt;<span class="built_in">status</span> ()) &amp;&amp; boost::filesystem::<span class="built_in">extension</span> (it-&gt;<span class="built_in">path</span> ()) == extension) <span class="comment">// 如果是普通文件且扩展名匹配</span></span><br><span class="line">    &#123;</span><br><span class="line">      vfh_model m;                               <span class="comment">// 创建一个新的vfh_model</span></span><br><span class="line">      <span class="keyword">if</span> (<span class="built_in">loadHist</span> (base_dir / it-&gt;<span class="built_in">path</span> ().<span class="built_in">filename</span> (), m)) <span class="comment">// 调用loadHist加载该文件</span></span><br><span class="line">        models.<span class="built_in">push_back</span> (m);                    <span class="comment">// 如果加载成功，将模型添加到models向量中</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">int</span></span></span><br><span class="line"><span class="function"><span class="title">main</span> <span class="params">(<span class="type">int</span> argc, <span class="type">char</span>** argv)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (argc &lt; <span class="number">2</span>)                                  <span class="comment">// 检查命令行参数数量</span></span><br><span class="line">  &#123;</span><br><span class="line">    <span class="built_in">PCL_ERROR</span> (<span class="string">&quot;Need at least two parameters! Syntax is: %s [model_directory] [options]\n&quot;</span>, argv[<span class="number">0</span>]); <span class="comment">// 如果参数不足，打印错误信息</span></span><br><span class="line">    <span class="keyword">return</span> (<span class="number">-1</span>);                                 <span class="comment">// 返回错误码</span></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function">std::string <span class="title">extension</span> <span class="params">(<span class="string">&quot;.pcd&quot;</span>)</span></span>;                <span class="comment">// 定义要查找的文件扩展名</span></span><br><span class="line">  <span class="built_in">transform</span> (extension.<span class="built_in">begin</span> (), extension.<span class="built_in">end</span> (), extension.<span class="built_in">begin</span> (), (<span class="built_in">int</span>(*)(<span class="type">int</span>))tolower); <span class="comment">// 将扩展名转换为小写</span></span><br><span class="line"></span><br><span class="line">  std::string kdtree_idx_file_name = <span class="string">&quot;kdtree.idx&quot;</span>; <span class="comment">// 定义FLANN索引文件的保存路径</span></span><br><span class="line">  std::string training_data_h5_file_name = <span class="string">&quot;training_data.h5&quot;</span>; <span class="comment">// 定义HDF5训练数据文件的保存路径</span></span><br><span class="line">  std::string training_data_list_file_name = <span class="string">&quot;training_data.list&quot;</span>; <span class="comment">// 定义模型文件列表的保存路径</span></span><br><span class="line"></span><br><span class="line">  std::vector&lt;vfh_model&gt; models;                 <span class="comment">// 声明一个向量，用于存储所有加载的VFH模型</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">// Load the model histograms</span></span><br><span class="line">  <span class="built_in">loadFeatureModels</span> (argv[<span class="number">1</span>], extension, models); <span class="comment">// 调用loadFeatureModels，从命令行指定的目录中递归加载所有.pcd文件</span></span><br><span class="line">  pcl::console::<span class="built_in">print_highlight</span> (<span class="string">&quot;Loaded %d VFH models. Creating training data %s/%s.\n&quot;</span>, </span><br><span class="line">      (<span class="type">int</span>)models.<span class="built_in">size</span> (), training_data_h5_file_name.<span class="built_in">c_str</span> (), training_data_list_file_name.<span class="built_in">c_str</span> ()); <span class="comment">// 打印加载完成信息</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">// Convert data into FLANN format</span></span><br><span class="line">  <span class="function">flann::Matrix&lt;<span class="type">float</span>&gt; <span class="title">data</span> <span class="params">(<span class="keyword">new</span> <span class="type">float</span>[models.size () * models[<span class="number">0</span>].second.size ()], models.size (), models[<span class="number">0</span>].second.size ())</span></span>; <span class="comment">// 创建一个FLANN矩阵，用于存储所有模型的特征向量</span></span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span> (<span class="type">size_t</span> i = <span class="number">0</span>; i &lt; data.rows; ++i)         <span class="comment">// 遍历每一行（每个模型）</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="type">size_t</span> j = <span class="number">0</span>; j &lt; data.cols; ++j)       <span class="comment">// 遍历每一列（特征向量的每个维度）</span></span><br><span class="line">      data[i][j] = models[i].second[j];          <span class="comment">// 将models向量中的特征值复制到data矩阵中</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">// Save data to disk (list of models)</span></span><br><span class="line">  flann::<span class="built_in">save_to_file</span> (data, training_data_h5_file_name, <span class="string">&quot;training_data&quot;</span>); <span class="comment">// 将data矩阵保存为HDF5文件</span></span><br><span class="line">  std::ofstream fs;                              <span class="comment">// 创建一个输出文件流</span></span><br><span class="line">  fs.<span class="built_in">open</span> (training_data_list_file_name.<span class="built_in">c_str</span> ()); <span class="comment">// 打开文本文件</span></span><br><span class="line">  <span class="keyword">for</span> (<span class="type">size_t</span> i = <span class="number">0</span>; i &lt; models.<span class="built_in">size</span> (); ++i)    <span class="comment">// 遍历所有模型</span></span><br><span class="line">    fs &lt;&lt; models[i].first &lt;&lt; <span class="string">&quot;\n&quot;</span>;               <span class="comment">// 将每个模型的文件路径写入文本文件</span></span><br><span class="line">  fs.<span class="built_in">close</span> ();                                   <span class="comment">// 关闭文件流</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">// Build the tree index and save it to disk</span></span><br><span class="line">  pcl::console::<span class="built_in">print_error</span> (<span class="string">&quot;Building the kdtree index (%s) for %d elements...\n&quot;</span>, kdtree_idx_file_name.<span class="built_in">c_str</span> (), (<span class="type">int</span>)data.rows); <span class="comment">// 打印正在构建索引的信息</span></span><br><span class="line">  flann::Index&lt;flann::ChiSquareDistance&lt;<span class="type">float</span>&gt; &gt; <span class="built_in">index</span> (data, flann::<span class="built_in">LinearIndexParams</span> ()); <span class="comment">// 创建一个FLANN索引对象，使用线性搜索（此处有误，应为KDTree等）</span></span><br><span class="line">  <span class="comment">//flann::Index&lt;flann::ChiSquareDistance&lt;float&gt; &gt; index (data, flann::KDTreeIndexParams (4)); // 正确的创建方式：使用KD树，4个树</span></span><br><span class="line">  index.<span class="built_in">buildIndex</span> ();                           <span class="comment">// 构建FLANN搜索索引</span></span><br><span class="line">  index.<span class="built_in">save</span> (kdtree_idx_file_name);             <span class="comment">// 将构建好的索引保存到文件</span></span><br><span class="line">  <span class="keyword">delete</span>[] data.<span class="built_in">ptr</span> ();                          <span class="comment">// 释放data矩阵分配的内存</span></span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> (<span class="number">0</span>);                                    <span class="comment">// 程序成功执行，返回0</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="nearest-neighbors-cpp-笔记"><a href="#nearest-neighbors-cpp-笔记" class="headerlink" title="nearest_neighbors.cpp 笔记"></a>nearest_neighbors.cpp 笔记</h1><p><code>nearest_neighbors.cpp</code> 是一个基于VFH特征的点云识别和可视化程序。它接收一个查询点云的VFH特征，利用FLANN索引在训练集中搜索最相似的模型，并将结果可视化。</p>
<h2 id="1-核心功能概述-1"><a href="#1-核心功能概述-1" class="headerlink" title="1. 核心功能概述"></a>1. 核心功能概述</h2><ol>
<li><strong>加载查询特征</strong>：从命令行指定的<code>.pcd</code>文件中加载一个查询点云的VFH特征。</li>
<li><strong>加载训练数据</strong>：从<code>training_data.list</code>和<code>training_data.h5</code>文件中加载所有训练模型的文件路径和VFH特征。</li>
<li><strong>加载搜索索引</strong>：从<code>kdtree.idx</code>文件中加载预先构建好的FLANN KD-Tree索引。</li>
<li><strong>执行KNN搜索</strong>：使用FLANN在训练集中搜索与查询特征最相似的k个模型。</li>
<li><strong>可视化结果</strong>：将搜索到的k个最相似点云模型在多个视口中并排显示，并用文本和红线进行标注。</li>
</ol>
<h2 id="2-重要数据结构-1"><a href="#2-重要数据结构-1" class="headerlink" title="2. 重要数据结构"></a>2. 重要数据结构</h2><ul>
<li><strong><code>vfh_model</code></strong>: <code>std::pair&lt;std::string, std::vector&lt;float&gt;&gt;</code>。用于存储一个VFH模型。<ul>
<li><code>first</code>: <code>std::string</code>，存储该模型对应的原始点云文件路径。</li>
<li><code>second</code>: <code>std::vector&lt;float&gt;</code>，存储308维的VFH特征向量。</li>
</ul>
</li>
<li><strong><code>flann::Matrix&lt;float&gt;</code></strong>: 一个<code>N x 308</code>的矩阵，存储所有训练模型的特征向量，是FLANN搜索的基础。</li>
<li><strong><code>flann::Matrix&lt;int&gt;</code> 和 <code>flann::Matrix&lt;float&gt;</code></strong>: 用于存储KNN搜索结果，分别存储最近邻的索引和距离。</li>
</ul>
<h2 id="3-关键函数-1"><a href="#3-关键函数-1" class="headerlink" title="3. 关键函数"></a>3. 关键函数</h2><h3 id="loadHist"><a href="#loadHist" class="headerlink" title="loadHist(...)"></a><code>loadHist(...)</code></h3><ul>
<li><strong>功能</strong>：从一个<code>.pcd</code>文件中加载VFH特征。</li>
<li><strong>步骤</strong>：<ol>
<li>通过<code>readHeader</code>检查文件是否为有效的VFH特征文件（包含”vfh”字段且为1x1）。</li>
<li>使用<code>loadPCDFile</code>加载完整的PCD文件。</li>
<li>将<code>pcl::VFHSignature308</code>点的<code>histogram</code>数组复制到<code>vfh</code>的<code>second</code>向量中。</li>
<li>将文件路径保存到<code>vfh</code>的<code>first</code>成员中。</li>
</ol>
</li>
</ul>
<h3 id="nearestKSearch"><a href="#nearestKSearch" class="headerlink" title="nearestKSearch(...)"></a><code>nearestKSearch(...)</code></h3><ul>
<li><strong>功能</strong>：对FLANN索引执行KNN搜索。</li>
<li><strong>步骤</strong>：<ol>
<li>将查询的VFH特征向量包装成一个<code>flann::Matrix&lt;float&gt;</code>。</li>
<li>为搜索结果（索引和距离）分配内存。</li>
<li>调用<code>index.knnSearch()</code>执行搜索。</li>
<li>释放查询向量的内存。</li>
</ol>
</li>
</ul>
<h3 id="loadFileList"><a href="#loadFileList" class="headerlink" title="loadFileList(...)"></a><code>loadFileList(...)</code></h3><ul>
<li><strong>功能</strong>：从一个<code>.list</code>文本文件中加载所有训练模型的文件路径。</li>
<li><strong>步骤</strong>：<ol>
<li>逐行读取文本文件。</li>
<li>忽略空行。</li>
<li>将每一行（一个文件路径）创建为一个<code>vfh_model</code>对象，并将其<code>first</code>成员设置为该路径，然后加入<code>models</code>向量。</li>
</ol>
</li>
</ul>
<h3 id="main-1"><a href="#main-1" class="headerlink" title="main(...)"></a><code>main(...)</code></h3><ul>
<li><strong>功能</strong>：程序主入口，协调整个识别和可视化流程。</li>
<li><strong>关键步骤</strong>：<ol>
<li><strong>参数解析</strong>：检查命令行参数，获取查询的VFH文件，并解析<code>-k</code>和<code>-thresh</code>选项。</li>
<li><strong>加载数据</strong>：调用<code>loadFileList</code>加载模型路径，调用<code>flann::load_from_file</code>加载特征数据矩阵。</li>
<li><strong>加载索引</strong>：使用<code>flann::SavedIndexParams</code>从<code>kdtree.idx</code>文件加载索引，<strong>不调用<code>buildIndex()</code></strong>。</li>
<li><strong>执行搜索</strong>：调用<code>nearestKSearch</code>获取k个最近邻。</li>
<li><strong>打印结果</strong>：在控制台打印搜索结果。</li>
<li><strong>可视化</strong>：<ul>
<li>创建<code>PCLVisualizer</code>对象。</li>
<li>根据k的数量计算并创建多个视口（<code>createViewPort</code>）。</li>
<li>对于每个最近邻：<ul>
<li>修正文件名（将<code>_vfh.pcd</code>改为<code>.pcd</code>以加载原始点云）。</li>
<li>加载对应的原始点云文件。</li>
<li>去中心化点云。</li>
<li>使用<strong>基于<code>viewport</code>的唯一ID</strong>（如<code>cloud_0</code>, <code>score_1</code>, <code>line_2</code>）将点云、距离文本和（如果需要）红线添加到对应的视口中。</li>
<li>添加文件名标签。</li>
</ul>
</li>
</ul>
</li>
<li><strong>启动可视化</strong>：调用<code>p.spin()</code>进入交互式显示。</li>
</ol>
</li>
</ul>
<h2 id="4-修复的关键问题"><a href="#4-修复的关键问题" class="headerlink" title="4. 修复的关键问题"></a>4. 修复的关键问题</h2><ol>
<li><strong><code>basic_string::_M_construct null not valid</code>崩溃</strong>：根本原因是使用了包含<code>/</code>的完整文件路径作为PCL可视化对象的ID。修复方法是使用<code>std::stringstream</code>生成基于<code>viewport</code>的唯一、安全的ID（如<code>label_0</code>）。</li>
<li><strong><code>boost::replace_last</code>不可用</strong>：使用<code>std::string::rfind</code>和<code>std::string::replace</code>安全地处理文件名后缀。</li>
<li><strong><code>index.buildIndex()</code>误用</strong>：当使用<code>SavedIndexParams</code>从文件加载索引时，不应再调用<code>buildIndex()</code>，否则会重新构建一个全新的索引，导致内存错误和结果不一致。</li>
<li><strong>索引越界检查</strong>：在访问<code>models</code>向量前，检查<code>k_indices[0][i]</code>是否在有效范围内，防止程序崩溃。</li>
<li><strong>头文件缺失</strong>：补充了<code>&lt;string&gt;</code>和<code>&lt;vector&gt;</code>头文件。</li>
</ol>
<h2 id="代码实现-1"><a href="#代码实现-1" class="headerlink" title="代码实现"></a>代码实现</h2><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br><span class="line">237</span><br><span class="line">238</span><br><span class="line">239</span><br><span class="line">240</span><br><span class="line">241</span><br><span class="line">242</span><br><span class="line">243</span><br><span class="line">244</span><br><span class="line">245</span><br><span class="line">246</span><br><span class="line">247</span><br><span class="line">248</span><br><span class="line">249</span><br><span class="line">250</span><br><span class="line">251</span><br><span class="line">252</span><br><span class="line">253</span><br><span class="line">254</span><br><span class="line">255</span><br><span class="line">256</span><br><span class="line">257</span><br><span class="line">258</span><br><span class="line">259</span><br><span class="line">260</span><br><span class="line">261</span><br><span class="line">262</span><br><span class="line">263</span><br><span class="line">264</span><br><span class="line">265</span><br><span class="line">266</span><br><span class="line">267</span><br><span class="line">268</span><br><span class="line">269</span><br><span class="line">270</span><br><span class="line">271</span><br><span class="line">272</span><br><span class="line">273</span><br><span class="line">274</span><br><span class="line">275</span><br><span class="line">276</span><br><span class="line">277</span><br><span class="line">278</span><br><span class="line">279</span><br><span class="line">280</span><br><span class="line">281</span><br><span class="line">282</span><br><span class="line">283</span><br><span class="line">284</span><br><span class="line">285</span><br><span class="line">286</span><br><span class="line">287</span><br><span class="line">288</span><br><span class="line">289</span><br><span class="line">290</span><br><span class="line">291</span><br><span class="line">292</span><br><span class="line">293</span><br><span class="line">294</span><br><span class="line">295</span><br><span class="line">296</span><br><span class="line">297</span><br><span class="line">298</span><br><span class="line">299</span><br><span class="line">300</span><br><span class="line">301</span><br><span class="line">302</span><br><span class="line">303</span><br><span class="line">304</span><br><span class="line">305</span><br><span class="line">306</span><br><span class="line">307</span><br><span class="line">308</span><br><span class="line">309</span><br><span class="line">310</span><br><span class="line">311</span><br><span class="line">312</span><br><span class="line">313</span><br><span class="line">314</span><br><span class="line">315</span><br><span class="line">316</span><br><span class="line">317</span><br><span class="line">318</span><br><span class="line">319</span><br><span class="line">320</span><br><span class="line">321</span><br><span class="line">322</span><br><span class="line">323</span><br><span class="line">324</span><br><span class="line">325</span><br><span class="line">326</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pcl/point_types.h&gt;</span>                     <span class="comment">// PCL点类型定义</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pcl/point_cloud.h&gt;</span>                     <span class="comment">// PCL点云数据结构</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pcl/common/common.h&gt;</span>                   <span class="comment">// PCL通用算法，如计算质心</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pcl/common/transforms.h&gt;</span>               <span class="comment">// PCL点云变换</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pcl/visualization/pcl_visualizer.h&gt;</span>    <span class="comment">// PCL可视化工具</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pcl/console/parse.h&gt;</span>                   <span class="comment">// PCL命令行解析</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pcl/console/print.h&gt;</span>                   <span class="comment">// PCL控制台输出</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pcl/io/pcd_io.h&gt;</span>                       <span class="comment">// PCL的PCD文件读写</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;iostream&gt;</span>                              <span class="comment">// C++标准输入输出</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;flann/flann.h&gt;</span>                         <span class="comment">// FLANN库主头文件</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;flann/io/hdf5.h&gt;</span>                       <span class="comment">// FLANN的HDF5文件读写</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;boost/filesystem.hpp&gt;</span>                  <span class="comment">// Boost文件系统库</span></span></span><br><span class="line"><span class="comment">// 修复：添加缺失的头文件</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;string&gt;</span>                                <span class="comment">// std::string</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;vector&gt;</span>                                <span class="comment">// std::vector</span></span></span><br><span class="line"></span><br><span class="line"><span class="keyword">typedef</span> std::pair&lt;std::string, std::vector&lt;<span class="type">float</span>&gt; &gt; vfh_model; <span class="comment">// 定义VFH模型类型，包含文件路径和特征向量</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/** \brief Loads an n-D histogram file as a VFH signature</span></span><br><span class="line"><span class="comment">  * \param path the input file name</span></span><br><span class="line"><span class="comment">  * \param vfh the resultant VFH model</span></span><br><span class="line"><span class="comment">  */</span></span><br><span class="line"><span class="function"><span class="type">bool</span></span></span><br><span class="line"><span class="function"><span class="title">loadHist</span> <span class="params">(<span class="type">const</span> boost::filesystem::path &amp;path, vfh_model &amp;vfh)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  <span class="type">int</span> vfh_idx;</span><br><span class="line">  <span class="comment">// Load the file as a PCD</span></span><br><span class="line">  <span class="keyword">try</span></span><br><span class="line">  &#123;</span><br><span class="line">    pcl::PCLPointCloud2 cloud;                   <span class="comment">// 用于存储PCD文件头信息</span></span><br><span class="line">    <span class="type">int</span> version;                                 <span class="comment">// PCD文件版本</span></span><br><span class="line">    Eigen::Vector4f origin;                      <span class="comment">// PCD文件原点</span></span><br><span class="line">    Eigen::Quaternionf orientation;              <span class="comment">// PCD文件朝向</span></span><br><span class="line">    pcl::PCDReader r;                            <span class="comment">// PCD文件读取器</span></span><br><span class="line">    <span class="type">int</span> type; <span class="type">unsigned</span> <span class="type">int</span> idx;                  <span class="comment">// PCD文件类型和索引</span></span><br><span class="line">    r.<span class="built_in">readHeader</span> (path.<span class="built_in">string</span> (), cloud, origin, orientation, version, type, idx); <span class="comment">// 读取PCD文件头</span></span><br><span class="line"></span><br><span class="line">    vfh_idx = pcl::<span class="built_in">getFieldIndex</span> (cloud, <span class="string">&quot;vfh&quot;</span>); <span class="comment">// 查找&quot;vfh&quot;字段的索引</span></span><br><span class="line">    <span class="keyword">if</span> (vfh_idx == <span class="number">-1</span>)                           <span class="comment">// 如果没有找到&quot;vfh&quot;字段</span></span><br><span class="line">      <span class="keyword">return</span> (<span class="literal">false</span>);                            <span class="comment">// 返回false</span></span><br><span class="line">    <span class="keyword">if</span> ((<span class="type">int</span>)cloud.width * cloud.height != <span class="number">1</span>)    <span class="comment">// VFH特征文件应为1x1</span></span><br><span class="line">      <span class="keyword">return</span> (<span class="literal">false</span>);                            <span class="comment">// 如果不是，返回false</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="built_in">catch</span> (pcl::InvalidConversionException &amp;e)     <span class="comment">// 捕获异常（修复：添加引用）</span></span><br><span class="line">  &#123;</span><br><span class="line">    <span class="keyword">return</span> (<span class="literal">false</span>);                              <span class="comment">// 发生异常，返回false</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// Treat the VFH signature as a single Point Cloud</span></span><br><span class="line">  pcl::PointCloud &lt;pcl::VFHSignature308&gt; point;  <span class="comment">// 声明一个VFH点云</span></span><br><span class="line">  pcl::io::<span class="built_in">loadPCDFile</span> (path.<span class="built_in">string</span> (), point);  <span class="comment">// 加载完整的PCD文件</span></span><br><span class="line">  vfh.second.<span class="built_in">resize</span> (<span class="number">308</span>);                       <span class="comment">// 为特征向量分配空间</span></span><br><span class="line"></span><br><span class="line">  std::vector &lt;pcl::PCLPointField&gt; fields;       <span class="comment">// 存储点云字段信息</span></span><br><span class="line">  pcl::<span class="built_in">getFieldIndex</span> (point, <span class="string">&quot;vfh&quot;</span>, fields);     <span class="comment">// 获取&quot;vfh&quot;字段信息</span></span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span> (<span class="type">size_t</span> i = <span class="number">0</span>; i &lt; fields[vfh_idx].count; ++i) <span class="comment">// 遍历308个特征值</span></span><br><span class="line">  &#123;</span><br><span class="line">    vfh.second[i] = point.points[<span class="number">0</span>].histogram[i]; <span class="comment">// 复制特征值</span></span><br><span class="line">  &#125;</span><br><span class="line">  vfh.first = path.<span class="built_in">string</span> ();                    <span class="comment">// 保存文件路径</span></span><br><span class="line">  <span class="keyword">return</span> (<span class="literal">true</span>);                                 <span class="comment">// 加载成功</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/** \brief Search for the closest k neighbors</span></span><br><span class="line"><span class="comment">  * \param index the tree</span></span><br><span class="line"><span class="comment">  * \param model the query model</span></span><br><span class="line"><span class="comment">  * \param k the number of neighbors to search for</span></span><br><span class="line"><span class="comment">  * \param indices the resultant neighbor indices</span></span><br><span class="line"><span class="comment">  * \param distances the resultant neighbor distances</span></span><br><span class="line"><span class="comment">  */</span></span><br><span class="line"><span class="function"><span class="keyword">inline</span> <span class="type">void</span></span></span><br><span class="line"><span class="function"><span class="title">nearestKSearch</span> <span class="params">(flann::Index&lt;flann::ChiSquareDistance&lt;<span class="type">float</span>&gt; &gt; &amp;index, <span class="type">const</span> vfh_model &amp;model, </span></span></span><br><span class="line"><span class="params"><span class="function">                <span class="type">int</span> k, flann::Matrix&lt;<span class="type">int</span>&gt; &amp;indices, flann::Matrix&lt;<span class="type">float</span>&gt; &amp;distances)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  <span class="comment">// Query point</span></span><br><span class="line">  flann::Matrix&lt;<span class="type">float</span>&gt; p = flann::<span class="built_in">Matrix</span>&lt;<span class="type">float</span>&gt;(<span class="keyword">new</span> <span class="type">float</span>[model.second.<span class="built_in">size</span> ()], <span class="number">1</span>, model.second.<span class="built_in">size</span> ()); <span class="comment">// 创建查询点矩阵</span></span><br><span class="line">  <span class="built_in">memcpy</span> (&amp;p.<span class="built_in">ptr</span> ()[<span class="number">0</span>], &amp;model.second[<span class="number">0</span>], p.cols * p.rows * <span class="built_in">sizeof</span> (<span class="type">float</span>)); <span class="comment">// 复制特征向量到矩阵</span></span><br><span class="line">  indices = flann::<span class="built_in">Matrix</span>&lt;<span class="type">int</span>&gt;(<span class="keyword">new</span> <span class="type">int</span>[k], <span class="number">1</span>, k); <span class="comment">// 为索引分配内存</span></span><br><span class="line">  distances = flann::<span class="built_in">Matrix</span>&lt;<span class="type">float</span>&gt;(<span class="keyword">new</span> <span class="type">float</span>[k], <span class="number">1</span>, k); <span class="comment">// 为距离分配内存</span></span><br><span class="line">  index.<span class="built_in">knnSearch</span> (p, indices, distances, k, flann::<span class="built_in">SearchParams</span> (<span class="number">512</span>)); <span class="comment">// 执行KNN搜索</span></span><br><span class="line">  <span class="keyword">delete</span>[] p.<span class="built_in">ptr</span> ();                             <span class="comment">// 释放查询点内存</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/** \brief Load the list of file model names from an ASCII file</span></span><br><span class="line"><span class="comment">  * \param models the resultant list of model name</span></span><br><span class="line"><span class="comment">  * \param filename the input file name</span></span><br><span class="line"><span class="comment">  */</span></span><br><span class="line"><span class="function"><span class="type">bool</span></span></span><br><span class="line"><span class="function"><span class="title">loadFileList</span> <span class="params">(std::vector&lt;vfh_model&gt; &amp;models, <span class="type">const</span> std::string &amp;filename)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  std::ifstream fs;                              <span class="comment">// 创建输入文件流</span></span><br><span class="line">  fs.<span class="built_in">open</span> (filename.<span class="built_in">c_str</span> ());                   <span class="comment">// 打开文件</span></span><br><span class="line">  <span class="keyword">if</span> (!fs.<span class="built_in">is_open</span> () || fs.<span class="built_in">fail</span> ())              <span class="comment">// 如果打开失败</span></span><br><span class="line">    <span class="keyword">return</span> (<span class="literal">false</span>);                              <span class="comment">// 返回false</span></span><br><span class="line">  std::string line;                              <span class="comment">// 存储每一行</span></span><br><span class="line">  <span class="keyword">while</span> (!fs.<span class="built_in">eof</span> ())                             <span class="comment">// 读取到文件末尾</span></span><br><span class="line">  &#123;</span><br><span class="line">    <span class="built_in">getline</span> (fs, line);                          <span class="comment">// 读取一行</span></span><br><span class="line">    <span class="keyword">if</span> (line.<span class="built_in">empty</span> ())                           <span class="comment">// 如果是空行</span></span><br><span class="line">      <span class="keyword">continue</span>;                                  <span class="comment">// 跳过</span></span><br><span class="line">    vfh_model m;                                 <span class="comment">// 创建一个vfh_model</span></span><br><span class="line">    m.first = line;                              <span class="comment">// 设置文件路径</span></span><br><span class="line">    models.<span class="built_in">push_back</span> (m);                        <span class="comment">// 添加到models向量</span></span><br><span class="line">  &#125;</span><br><span class="line">  fs.<span class="built_in">close</span> ();                                   <span class="comment">// 关闭文件</span></span><br><span class="line">  <span class="keyword">return</span> (<span class="literal">true</span>);                                 <span class="comment">// 加载成功</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">int</span></span></span><br><span class="line"><span class="function"><span class="title">main</span> <span class="params">(<span class="type">int</span> argc, <span class="type">char</span>** argv)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  <span class="type">int</span> k = <span class="number">6</span>;                                     <span class="comment">// 默认k值</span></span><br><span class="line">  <span class="type">double</span> thresh = DBL_MAX;                       <span class="comment">// 默认阈值（禁用）</span></span><br><span class="line">  <span class="keyword">if</span> (argc &lt; <span class="number">2</span>)                                  <span class="comment">// 检查参数数量</span></span><br><span class="line">  &#123;</span><br><span class="line">    pcl::console::<span class="built_in">print_error</span> (<span class="string">&quot;Need at least one parameter! Syntax is: %s &lt;query_vfh_model.pcd&gt; [options] &#123;kdtree.idx&#125; &#123;training_data.h5&#125; &#123;training_data.list&#125;\n&quot;</span>, argv[<span class="number">0</span>]); <span class="comment">// 打印错误信息</span></span><br><span class="line">    pcl::console::<span class="built_in">print_info</span> (<span class="string">&quot;    where [options] are:  -k      = number of nearest neighbors to search for in the tree (default: &quot;</span>); </span><br><span class="line">    pcl::console::<span class="built_in">print_value</span> (<span class="string">&quot;%d&quot;</span>, k); pcl::console::<span class="built_in">print_info</span> (<span class="string">&quot;)\n&quot;</span>);</span><br><span class="line">    pcl::console::<span class="built_in">print_info</span> (<span class="string">&quot;                          -thresh = maximum distance threshold for a model to be considered VALID (default: &quot;</span>); </span><br><span class="line">    pcl::console::<span class="built_in">print_value</span> (<span class="string">&quot;%f&quot;</span>, thresh); pcl::console::<span class="built_in">print_info</span> (<span class="string">&quot;)\n&quot;</span>);</span><br><span class="line">    <span class="keyword">return</span> (<span class="number">-1</span>);                                 <span class="comment">// 返回错误码</span></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function">std::string <span class="title">extension</span> <span class="params">(<span class="string">&quot;.pcd&quot;</span>)</span></span>;                <span class="comment">// 文件扩展名</span></span><br><span class="line">  std::<span class="built_in">transform</span> (extension.<span class="built_in">begin</span> (), extension.<span class="built_in">end</span> (), extension.<span class="built_in">begin</span> (), ::tolower); <span class="comment">// 转换为小写</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">// Load the test histogram</span></span><br><span class="line">  std::vector&lt;<span class="type">int</span>&gt; pcd_indices = pcl::console::<span class="built_in">parse_file_extension_argument</span> (argc, argv, <span class="string">&quot;.pcd&quot;</span>); <span class="comment">// 解析命令行中的PCD文件</span></span><br><span class="line">  <span class="keyword">if</span> (pcd_indices.<span class="built_in">empty</span>())                       <span class="comment">// 如果没有找到PCD文件</span></span><br><span class="line">  &#123;</span><br><span class="line">    pcl::console::<span class="built_in">print_error</span>(<span class="string">&quot;No PCD file found in the command line arguments.\n&quot;</span>); <span class="comment">// 打印错误</span></span><br><span class="line">    <span class="keyword">return</span> <span class="number">-1</span>;                                   <span class="comment">// 返回错误</span></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  vfh_model histogram;                           <span class="comment">// 存储查询的VFH模型</span></span><br><span class="line">  <span class="keyword">if</span> (!<span class="built_in">loadHist</span> (argv[pcd_indices.<span class="built_in">at</span> (<span class="number">0</span>)], histogram)) <span class="comment">// 加载查询的VFH特征</span></span><br><span class="line">  &#123;</span><br><span class="line">    pcl::console::<span class="built_in">print_error</span> (<span class="string">&quot;Cannot load test file %s\n&quot;</span>, argv[pcd_indices.<span class="built_in">at</span> (<span class="number">0</span>)]); <span class="comment">// 加载失败</span></span><br><span class="line">    <span class="keyword">return</span> (<span class="number">-1</span>);                                 <span class="comment">// 返回错误</span></span><br><span class="line">  &#125;</span><br><span class="line">  pcl::console::<span class="built_in">parse_argument</span> (argc, argv, <span class="string">&quot;-thresh&quot;</span>, thresh); <span class="comment">// 解析-thresh参数</span></span><br><span class="line">  <span class="comment">// Search for the k closest matches</span></span><br><span class="line">  pcl::console::<span class="built_in">parse_argument</span> (argc, argv, <span class="string">&quot;-k&quot;</span>, k); <span class="comment">// 解析-k参数</span></span><br><span class="line">  pcl::console::<span class="built_in">print_highlight</span> (<span class="string">&quot;Using &quot;</span>); pcl::console::<span class="built_in">print_value</span> (<span class="string">&quot;%d&quot;</span>, k); pcl::console::<span class="built_in">print_info</span> (<span class="string">&quot; nearest neighbors.\n&quot;</span>); <span class="comment">// 打印信息</span></span><br><span class="line"></span><br><span class="line">  std::string kdtree_idx_file_name = <span class="string">&quot;kdtree.idx&quot;</span>; <span class="comment">// 索引文件名</span></span><br><span class="line">  std::string training_data_h5_file_name = <span class="string">&quot;training_data.h5&quot;</span>; <span class="comment">// HDF5数据文件名</span></span><br><span class="line">  std::string training_data_list_file_name = <span class="string">&quot;training_data.list&quot;</span>; <span class="comment">// 文件列表名</span></span><br><span class="line">  std::vector&lt;vfh_model&gt; models;                 <span class="comment">// 存储训练模型</span></span><br><span class="line">  flann::Matrix&lt;<span class="type">int</span>&gt; k_indices;                  <span class="comment">// 存储搜索结果索引</span></span><br><span class="line">  flann::Matrix&lt;<span class="type">float</span>&gt; k_distances;              <span class="comment">// 存储搜索结果距离</span></span><br><span class="line">  flann::Matrix&lt;<span class="type">float</span>&gt; data;                     <span class="comment">// 存储从HDF5加载的特征数据</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">// Check if the data has already been saved to disk</span></span><br><span class="line">  <span class="keyword">if</span> (!boost::filesystem::<span class="built_in">exists</span> (training_data_h5_file_name) || !boost::filesystem::<span class="built_in">exists</span> (training_data_list_file_name)) <span class="comment">// 检查训练数据文件是否存在</span></span><br><span class="line">  &#123;</span><br><span class="line">    pcl::console::<span class="built_in">print_error</span> (<span class="string">&quot;Could not find training data models files %s and %s!\n&quot;</span>, </span><br><span class="line">        training_data_h5_file_name.<span class="built_in">c_str</span> (), training_data_list_file_name.<span class="built_in">c_str</span> ()); <span class="comment">// 打印错误</span></span><br><span class="line">    <span class="keyword">return</span> (<span class="number">-1</span>);                                 <span class="comment">// 返回错误</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">else</span></span><br><span class="line">  &#123;</span><br><span class="line">    <span class="keyword">if</span> (!<span class="built_in">loadFileList</span> (models, training_data_list_file_name)) <span class="comment">// 加载文件列表</span></span><br><span class="line">    &#123;</span><br><span class="line">      pcl::console::<span class="built_in">print_error</span>(<span class="string">&quot;Failed to load file list from %s\n&quot;</span>, training_data_list_file_name.<span class="built_in">c_str</span>()); <span class="comment">// 加载失败</span></span><br><span class="line">      <span class="keyword">return</span> <span class="number">-1</span>;                                 <span class="comment">// 返回错误</span></span><br><span class="line">    &#125;</span><br><span class="line">    flann::<span class="built_in">load_from_file</span> (data, training_data_h5_file_name, <span class="string">&quot;training_data&quot;</span>); <span class="comment">// 从HDF5加载特征数据</span></span><br><span class="line">    pcl::console::<span class="built_in">print_highlight</span> (<span class="string">&quot;Training data found. Loaded %d VFH models from %s/%s.\n&quot;</span>, </span><br><span class="line">        (<span class="type">int</span>)data.rows, training_data_h5_file_name.<span class="built_in">c_str</span> (), training_data_list_file_name.<span class="built_in">c_str</span> ()); <span class="comment">// 打印信息</span></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// Check if the tree index has already been saved to disk</span></span><br><span class="line">  <span class="keyword">if</span> (!boost::filesystem::<span class="built_in">exists</span> (kdtree_idx_file_name)) <span class="comment">// 检查索引文件是否存在</span></span><br><span class="line">  &#123;</span><br><span class="line">    pcl::console::<span class="built_in">print_error</span> (<span class="string">&quot;Could not find kd-tree index in file %s!\n&quot;</span>, kdtree_idx_file_name.<span class="built_in">c_str</span> ()); <span class="comment">// 打印错误</span></span><br><span class="line">    <span class="keyword">return</span> (<span class="number">-1</span>);                                 <span class="comment">// 返回错误</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">else</span></span><br><span class="line">  &#123;</span><br><span class="line">    <span class="comment">// 修复：使用 SavedIndexParams 加载，不要调用 buildIndex()</span></span><br><span class="line">    flann::Index&lt;flann::ChiSquareDistance&lt;<span class="type">float</span>&gt; &gt; <span class="built_in">index</span> (data, flann::<span class="built_in">SavedIndexParams</span> (kdtree_idx_file_name)); <span class="comment">// 从文件加载索引</span></span><br><span class="line">    <span class="comment">// index.buildIndex (); // ❌ 删除这行，buildIndex 与 SavedIndexParams 冲突</span></span><br><span class="line">    <span class="built_in">nearestKSearch</span> (index, histogram, k, k_indices, k_distances); <span class="comment">// 执行KNN搜索</span></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// Output the results on screen</span></span><br><span class="line">  pcl::console::<span class="built_in">print_highlight</span> (<span class="string">&quot;The closest %d neighbors for %s are:\n&quot;</span>, k, argv[pcd_indices[<span class="number">0</span>]]); <span class="comment">// 打印结果标题</span></span><br><span class="line">  <span class="keyword">for</span> (<span class="type">int</span> i = <span class="number">0</span>; i &lt; k; ++i)                    <span class="comment">// 遍历k个最近邻</span></span><br><span class="line">  &#123;</span><br><span class="line">    <span class="comment">// 修复：检查索引有效性</span></span><br><span class="line">    <span class="keyword">if</span> (k_indices[<span class="number">0</span>][i] &lt; <span class="number">0</span> || k_indices[<span class="number">0</span>][i] &gt;= <span class="built_in">static_cast</span>&lt;<span class="type">int</span>&gt;(models.<span class="built_in">size</span>())) <span class="comment">// 检查索引是否越界</span></span><br><span class="line">    &#123;</span><br><span class="line">      pcl::console::<span class="built_in">print_error</span>(<span class="string">&quot;Invalid neighbor index: %d\n&quot;</span>, k_indices[<span class="number">0</span>][i]); <span class="comment">// 打印错误</span></span><br><span class="line">      <span class="keyword">continue</span>;                                  <span class="comment">// 跳过</span></span><br><span class="line">    &#125;</span><br><span class="line">    pcl::console::<span class="built_in">print_info</span> (<span class="string">&quot;    %d - %s (%d) with a distance of: %f\n&quot;</span>, </span><br><span class="line">        i, models.<span class="built_in">at</span> (k_indices[<span class="number">0</span>][i]).first.<span class="built_in">c_str</span> (), k_indices[<span class="number">0</span>][i], k_distances[<span class="number">0</span>][i]); <span class="comment">// 打印每个邻居的信息</span></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// Load the results</span></span><br><span class="line">  pcl::<span class="function">visualization::PCLVisualizer <span class="title">p</span> <span class="params">(argc, argv, <span class="string">&quot;VFH Cluster Classifier&quot;</span>)</span></span>; <span class="comment">// 创建可视化窗口</span></span><br><span class="line">  <span class="type">int</span> y_s = (<span class="type">int</span>)<span class="built_in">floor</span> (<span class="built_in">sqrt</span> ((<span class="type">double</span>)k));       <span class="comment">// 计算视口行数</span></span><br><span class="line">  <span class="type">int</span> x_s = y_s + (<span class="type">int</span>)<span class="built_in">ceil</span> ((k / (<span class="type">double</span>)y_s) - y_s); <span class="comment">// 计算视口列数</span></span><br><span class="line">  <span class="type">double</span> x_step = (<span class="type">double</span>)(<span class="number">1.0</span> / (<span class="type">double</span>)x_s);   <span class="comment">// 计算每个视口的宽度</span></span><br><span class="line">  <span class="type">double</span> y_step = (<span class="type">double</span>)(<span class="number">1.0</span> / (<span class="type">double</span>)y_s);   <span class="comment">// 计算每个视口的高度</span></span><br><span class="line">  pcl::console::<span class="built_in">print_highlight</span> (<span class="string">&quot;Preparing to load &quot;</span>); </span><br><span class="line">  pcl::console::<span class="built_in">print_value</span> (<span class="string">&quot;%d&quot;</span>, k); </span><br><span class="line">  pcl::console::<span class="built_in">print_info</span> (<span class="string">&quot; files (&quot;</span>); </span><br><span class="line">  pcl::console::<span class="built_in">print_value</span> (<span class="string">&quot;%d&quot;</span>, x_s);    </span><br><span class="line">  pcl::console::<span class="built_in">print_info</span> (<span class="string">&quot;x&quot;</span>); </span><br><span class="line">  pcl::console::<span class="built_in">print_value</span> (<span class="string">&quot;%d&quot;</span>, y_s); </span><br><span class="line">  pcl::console::<span class="built_in">print_info</span> (<span class="string">&quot; / &quot;</span>);</span><br><span class="line">  pcl::console::<span class="built_in">print_value</span> (<span class="string">&quot;%f&quot;</span>, x_step); </span><br><span class="line">  pcl::console::<span class="built_in">print_info</span> (<span class="string">&quot;x&quot;</span>); </span><br><span class="line">  pcl::console::<span class="built_in">print_value</span> (<span class="string">&quot;%f&quot;</span>, y_step); </span><br><span class="line">  pcl::console::<span class="built_in">print_info</span> (<span class="string">&quot;)\n&quot;</span>);</span><br><span class="line"></span><br><span class="line">  <span class="type">int</span> viewport = <span class="number">0</span>, l = <span class="number">0</span>, m = <span class="number">0</span>;                <span class="comment">// 视口计数器和行列计数器</span></span><br><span class="line">  <span class="keyword">for</span> (<span class="type">int</span> i = <span class="number">0</span>; i &lt; k; ++i)                    <span class="comment">// 遍历k个最近邻</span></span><br><span class="line">  &#123;</span><br><span class="line">    <span class="comment">// 修复：检查索引有效性</span></span><br><span class="line">    <span class="keyword">if</span> (k_indices[<span class="number">0</span>][i] &lt; <span class="number">0</span> || k_indices[<span class="number">0</span>][i] &gt;= <span class="built_in">static_cast</span>&lt;<span class="type">int</span>&gt;(models.<span class="built_in">size</span>())) <span class="comment">// 检查索引是否有效</span></span><br><span class="line">    &#123;</span><br><span class="line">      pcl::console::<span class="built_in">print_error</span>(<span class="string">&quot;Skipping invalid neighbor index: %d\n&quot;</span>, k_indices[<span class="number">0</span>][i]); <span class="comment">// 打印错误</span></span><br><span class="line">      <span class="keyword">continue</span>;                                  <span class="comment">// 跳过</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    std::string cloud_name = models.<span class="built_in">at</span> (k_indices[<span class="number">0</span>][i]).first; <span class="comment">// 获取模型文件路径</span></span><br><span class="line">    <span class="comment">// 修复：安全地移除 &quot;_vfh.pcd&quot; 后缀</span></span><br><span class="line">    <span class="type">size_t</span> pos = cloud_name.<span class="built_in">rfind</span>(<span class="string">&quot;_vfh.pcd&quot;</span>);   <span class="comment">// 查找&quot;_vfh.pcd&quot;</span></span><br><span class="line">    <span class="keyword">if</span> (pos != std::string::npos)                <span class="comment">// 如果找到</span></span><br><span class="line">    &#123;</span><br><span class="line">      cloud_name.<span class="built_in">replace</span>(pos, <span class="number">8</span>, <span class="string">&quot;.pcd&quot;</span>);        <span class="comment">// 替换为&quot;.pcd&quot;</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span></span><br><span class="line">    &#123;</span><br><span class="line">      <span class="comment">// 如果没有找到，尝试移除 &quot;_vfh&quot;</span></span><br><span class="line">      pos = cloud_name.<span class="built_in">rfind</span>(<span class="string">&quot;_vfh&quot;</span>);            <span class="comment">// 查找&quot;_vfh&quot;</span></span><br><span class="line">      <span class="keyword">if</span> (pos != std::string::npos)              <span class="comment">// 如果找到</span></span><br><span class="line">      &#123;</span><br><span class="line">        cloud_name.<span class="built_in">replace</span>(pos, <span class="number">4</span>, <span class="string">&quot;&quot;</span>);          <span class="comment">// 移除&quot;_vfh&quot;</span></span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">// 如果还是找不到，保留原名</span></span><br><span class="line">      pcl::console::<span class="built_in">print_warn</span>(<span class="string">&quot;Filename does not have &#x27;_vfh&#x27; suffix: %s\n&quot;</span>, cloud_name.<span class="built_in">c_str</span>()); <span class="comment">// 打印警告</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    p.<span class="built_in">createViewPort</span> (l * x_step, m * y_step, (l + <span class="number">1</span>) * x_step, (m + <span class="number">1</span>) * y_step, viewport); <span class="comment">// 创建视口</span></span><br><span class="line">    l++;</span><br><span class="line">    <span class="keyword">if</span> (l &gt;= x_s)</span><br><span class="line">    &#123;</span><br><span class="line">      l = <span class="number">0</span>;</span><br><span class="line">      m++;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    pcl::PCLPointCloud2 cloud;                   <span class="comment">// 存储加载的PCD数据</span></span><br><span class="line">    pcl::console::<span class="built_in">print_highlight</span> (<span class="string">&quot;Loading &quot;</span>); pcl::console::<span class="built_in">print_value</span> (<span class="string">&quot;%s &quot;</span>, cloud_name.<span class="built_in">c_str</span> ()); <span class="comment">// 打印加载信息</span></span><br><span class="line">    <span class="keyword">if</span> (pcl::io::<span class="built_in">loadPCDFile</span> (cloud_name, cloud) == <span class="number">-1</span>) <span class="comment">// 加载PCD文件</span></span><br><span class="line">    &#123;</span><br><span class="line">      pcl::console::<span class="built_in">print_error</span>(<span class="string">&quot;Failed to load %s\n&quot;</span>, cloud_name.<span class="built_in">c_str</span>()); <span class="comment">// 加载失败</span></span><br><span class="line">      viewport++;                                <span class="comment">// 递增视口计数器</span></span><br><span class="line">      <span class="keyword">continue</span>;                                  <span class="comment">// 跳过</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Convert from blob to PointCloud</span></span><br><span class="line">    pcl::PointCloud&lt;pcl::PointXYZ&gt; cloud_xyz;    <span class="comment">// 存储转换后的点云</span></span><br><span class="line">    pcl::<span class="built_in">fromPCLPointCloud2</span> (cloud, cloud_xyz);  <span class="comment">// 转换数据类型</span></span><br><span class="line">    <span class="keyword">if</span> (cloud_xyz.points.<span class="built_in">empty</span>())                <span class="comment">// 如果点云为空</span></span><br><span class="line">    &#123;</span><br><span class="line">      pcl::console::<span class="built_in">print_error</span>(<span class="string">&quot;Loaded point cloud is empty: %s\n&quot;</span>, cloud_name.<span class="built_in">c_str</span>()); <span class="comment">// 打印错误</span></span><br><span class="line">      viewport++;</span><br><span class="line">      <span class="keyword">continue</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    pcl::console::<span class="built_in">print_info</span> (<span class="string">&quot;[done, %zu points]\n&quot;</span>, cloud_xyz.points.<span class="built_in">size</span>()); <span class="comment">// 打印加载成功</span></span><br><span class="line">    pcl::console::<span class="built_in">print_info</span> (<span class="string">&quot;Available dimensions: %s\n&quot;</span>, pcl::<span class="built_in">getFieldsList</span> (cloud).<span class="built_in">c_str</span> ()); <span class="comment">// 打印字段信息</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// Demean the cloud</span></span><br><span class="line">    Eigen::Vector4f centroid;                    <span class="comment">// 存储质心</span></span><br><span class="line">    pcl::<span class="built_in">compute3DCentroid</span> (cloud_xyz, centroid); <span class="comment">// 计算质心</span></span><br><span class="line">    pcl::PointCloud&lt;pcl::PointXYZ&gt;::<span class="function">Ptr <span class="title">cloud_xyz_demean</span> <span class="params">(<span class="keyword">new</span> pcl::PointCloud&lt;pcl::PointXYZ&gt;)</span></span>; <span class="comment">// 创建去中心化点云</span></span><br><span class="line">    pcl::<span class="built_in">demeanPointCloud</span>&lt;pcl::PointXYZ&gt; (cloud_xyz, centroid, *cloud_xyz_demean); <span class="comment">// 去中心化</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// 修复：使用基于viewport的唯一ID</span></span><br><span class="line">    std::stringstream cloud_id;                  <span class="comment">// 创建ID</span></span><br><span class="line">    cloud_id &lt;&lt; <span class="string">&quot;cloud_&quot;</span> &lt;&lt; viewport;            <span class="comment">// ID为 &quot;cloud_0&quot;, &quot;cloud_1&quot;, ...</span></span><br><span class="line">    p.<span class="built_in">addPointCloud</span> (cloud_xyz_demean, cloud_id.<span class="built_in">str</span>(), viewport); <span class="comment">// 添加点云到视口</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// Check if the model found is within our inlier tolerance</span></span><br><span class="line">    std::stringstream ss;                        <span class="comment">// 创建字符串流</span></span><br><span class="line">    ss &lt;&lt; std::fixed &lt;&lt; std::<span class="built_in">setprecision</span>(<span class="number">6</span>) &lt;&lt; k_distances[<span class="number">0</span>][i]; <span class="comment">// 格式化距离</span></span><br><span class="line">    std::stringstream score_id;                  <span class="comment">// 创建分数文本ID</span></span><br><span class="line">    score_id &lt;&lt; <span class="string">&quot;score_&quot;</span> &lt;&lt; viewport;            <span class="comment">// ID为 &quot;score_0&quot;, &quot;score_1&quot;, ...</span></span><br><span class="line">    <span class="keyword">if</span> (k_distances[<span class="number">0</span>][i] &gt; thresh)              <span class="comment">// 如果距离大于阈值</span></span><br><span class="line">    &#123;</span><br><span class="line">      p.<span class="built_in">addText</span> (ss.<span class="built_in">str</span> (), <span class="number">20</span>, <span class="number">30</span>, <span class="number">1</span>, <span class="number">0</span>, <span class="number">0</span>, score_id.<span class="built_in">str</span> (), viewport);  <span class="comment">// 添加红色文本</span></span><br><span class="line">      <span class="comment">// Create a red line（创建一条红线）</span></span><br><span class="line">      pcl::PointXYZ min_p, max_p;                <span class="comment">// 存储点云的最小最大点</span></span><br><span class="line">      pcl::<span class="built_in">getMinMax3D</span> (*cloud_xyz_demean, min_p, max_p); <span class="comment">// 获取边界</span></span><br><span class="line">      std::stringstream line_name;               <span class="comment">// 创建线ID</span></span><br><span class="line">      line_name &lt;&lt; <span class="string">&quot;line_&quot;</span> &lt;&lt; viewport;          <span class="comment">// ID为 &quot;line_0&quot;, &quot;line_1&quot;, ...</span></span><br><span class="line">      p.<span class="built_in">addLine</span> (min_p, max_p, <span class="number">1</span>, <span class="number">0</span>, <span class="number">0</span>, line_name.<span class="built_in">str</span> (), viewport); <span class="comment">// 添加红线</span></span><br><span class="line">      p.<span class="built_in">setShapeRenderingProperties</span> (pcl::visualization::PCL_VISUALIZER_LINE_WIDTH, <span class="number">5</span>, line_name.<span class="built_in">str</span> (), viewport); <span class="comment">// 设置线宽</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span></span><br><span class="line">    &#123;</span><br><span class="line">      p.<span class="built_in">addText</span> (ss.<span class="built_in">str</span> (), <span class="number">20</span>, <span class="number">30</span>, <span class="number">0</span>, <span class="number">1</span>, <span class="number">0</span>, score_id.<span class="built_in">str</span> (), viewport); <span class="comment">// 添加绿色文本</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// Increase the font size for the score*</span></span><br><span class="line">    p.<span class="built_in">setShapeRenderingProperties</span> (pcl::visualization::PCL_VISUALIZER_FONT_SIZE, <span class="number">18</span>, score_id.<span class="built_in">str</span> (), viewport); <span class="comment">// 设置字体大小</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// Add the cluster name（添加聚类名称）</span></span><br><span class="line">    <span class="comment">// 修复：使用基于viewport的唯一ID，并只显示文件名</span></span><br><span class="line">    boost::<span class="function">filesystem::path <span class="title">pth</span><span class="params">(cloud_name)</span></span>;     <span class="comment">// 解析文件路径</span></span><br><span class="line">    std::string filename = pth.<span class="built_in">filename</span>().<span class="built_in">string</span>(); <span class="comment">// 获取文件名</span></span><br><span class="line">    std::stringstream label_id;                  <span class="comment">// 创建标签ID</span></span><br><span class="line">    label_id &lt;&lt; <span class="string">&quot;label_&quot;</span> &lt;&lt; viewport;            <span class="comment">// ID为 &quot;label_0&quot;, &quot;label_1&quot;, ...</span></span><br><span class="line">    p.<span class="built_in">addText</span> (filename, <span class="number">20</span>, <span class="number">10</span>, label_id.<span class="built_in">str</span> (), viewport); <span class="comment">// 添加文件名标签</span></span><br><span class="line"></span><br><span class="line">    viewport++; <span class="comment">// 重要：在循环末尾递增viewport</span></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// Add coordinate systems to all viewports（给所有的窗口添加坐标系统）</span></span><br><span class="line">  p.<span class="built_in">addCoordinateSystem</span> (<span class="number">0.1</span>);                   <span class="comment">// 添加坐标系</span></span><br><span class="line">  p.<span class="built_in">spin</span> ();                                     <span class="comment">// 进入可视化循环</span></span><br><span class="line">  <span class="keyword">return</span> (<span class="number">0</span>);                                    <span class="comment">// 程序成功</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><img src="https://ckyfi9zero.github.io/picx-images-hosting/20250804/image.4cl74kmu5d.webp" alt="image"></p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta"><i class="fas fa-circle-user fa-fw"></i>文章作者: </span><span class="post-copyright-info"><a href="https://ckyfi9zero.github.io">Fi9zero</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta"><i class="fas fa-square-arrow-up-right fa-fw"></i>文章链接: </span><span class="post-copyright-info"><a href="https://ckyfi9zero.github.io/2025/08/04/2025-08-04-%E5%9F%BA%E4%BA%8EVFH%E6%8F%8F%E8%BF%B0%E8%87%AA%E8%81%9A%E7%B1%BB%E8%AF%86%E5%88%AB%E4%B8%8E%E4%BD%8D%E5%A7%BF%E4%BC%B0%E8%AE%A1/">https://ckyfi9zero.github.io/2025/08/04/2025-08-04-%E5%9F%BA%E4%BA%8EVFH%E6%8F%8F%E8%BF%B0%E8%87%AA%E8%81%9A%E7%B1%BB%E8%AF%86%E5%88%AB%E4%B8%8E%E4%BD%8D%E5%A7%BF%E4%BC%B0%E8%AE%A1/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta"><i class="fas fa-circle-exclamation fa-fw"></i>版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来源 <a href="https://ckyfi9zero.github.io" target="_blank">荒岛</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/c/">c++</a><a class="post-meta__tags" href="/tags/PCL/">PCL</a></div><div class="post-share"><div class="social-share" data-image="/image/avatar.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><a class="pagination-related  no-desc" href="/2025/08/04/2025-08-04-%E5%B9%B3%E9%9D%A2%E6%A8%A1%E5%9E%8B%E5%88%86%E5%89%B2/" title="平面模型分割"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info"><div class="info-1"><div class="info-item-1">上一篇</div><div class="info-item-2">平面模型分割</div></div></div></a><a class="pagination-related  no-desc" href="/2025/08/04/2025-08-04-%E6%89%AB%E6%8F%8F%E6%95%B0%E6%8D%AE%E4%B8%8E%E6%A8%A1%E6%9D%BF%E5%AF%B9%E8%B1%A1%E8%BF%9B%E8%A1%8C%E9%85%8D%E5%87%86/" title="扫描数据与模板对象进行配准"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-right"><div class="info-1"><div class="info-item-1">下一篇</div><div class="info-item-2">扫描数据与模板对象进行配准</div></div></div></a></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><a class="pagination-related no-desc" href="/2025/07/31/2025-07-31-%E7%94%A8kdtree%E5%AE%9E%E7%8E%B0%E5%BF%AB%E9%80%9F%E9%A2%86%E5%9F%9F%E6%90%9C%E7%B4%A2/" title="用kdtree实现快速领域搜索"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2025-07-31</div><div class="info-item-2">用kdtree实现快速领域搜索</div></div></div></a><a class="pagination-related no-desc" href="/2025/07/31/2025-07-31-%E7%94%A8%E5%85%AB%E5%8F%89%E6%A0%91%E8%BF%9B%E8%A1%8C%E6%97%A0%E5%BA%8F%E7%82%B9%E4%BA%91%E6%95%B0%E6%8D%AE%E7%9A%84%E7%A9%BA%E9%97%B4%E5%8F%98%E5%8C%96%E6%A3%80%E6%B5%8B/" title="用八叉树进行无序点云数据的空间变化检测"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2025-07-31</div><div class="info-item-2">用八叉树进行无序点云数据的空间变化检测</div></div></div></a><a class="pagination-related no-desc" href="/2025/07/31/2025-07-31-%E7%94%A8%E7%9B%B4%E9%80%9A%E6%BB%A4%E6%B3%A2%E5%99%A8%E5%AF%B9%E7%82%B9%E4%BA%91%E8%BF%9B%E8%A1%8C%E6%BB%A4%E6%B3%A2%E5%A4%84%E7%90%86/" title="用直通滤波器对点云进行滤波处理"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2025-07-31</div><div class="info-item-2">用直通滤波器对点云进行滤波处理</div></div></div></a><a class="pagination-related no-desc" href="/2025/08/01/2025-08-01-%E4%BB%8E%E7%82%B9%E4%BA%91%E5%88%9B%E5%BB%BA%E4%B8%80%E4%B8%AA%E6%B7%B1%E5%BA%A6%E5%9B%BE%E5%83%8F/" title="从点云创建一个深度图像"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2025-08-01</div><div class="info-item-2">从点云创建一个深度图像</div></div></div></a><a class="pagination-related no-desc" href="/2025/08/01/2025-08-01-%E4%BB%8E%E4%B8%80%E4%B8%AA%E7%82%B9%E4%BA%91%E4%B8%AD%E6%8F%90%E5%8F%96%E4%B8%80%E4%B8%AA%E5%AD%90%E9%9B%86/" title="从一个点云中提取一个子集"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2025-08-01</div><div class="info-item-2">从一个点云中提取一个子集</div></div></div></a><a class="pagination-related no-desc" href="/2025/08/01/2025-08-01-%E5%9C%A8%E6%BB%A4%E6%B3%A2%E5%99%A8%E6%A8%A1%E5%9D%97%E7%A7%BB%E9%99%A4%E7%A6%BB%E7%BE%A4%E7%82%B9/" title="在滤波器模块移除离群点"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2025-08-01</div><div class="info-item-2">在滤波器模块移除离群点</div></div></div></a></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info text-center"><div class="avatar-img"><img src="/image/avatar.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info-name">Fi9zero</div><div class="author-info-description"></div><div class="site-data"><a href="/archives/"><div class="headline">文章</div><div class="length-num">54</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">15</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">8</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/ckyFi9zero"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons"><a class="social-icon" href="https://github.com/ckyFi9zero" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="mailto:2539894206@qq.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#build-tree-cpp"><span class="toc-number">1.</span> <span class="toc-text">build_tree.cpp</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-%E6%A0%B8%E5%BF%83%E5%8A%9F%E8%83%BD%E6%A6%82%E8%BF%B0"><span class="toc-number">1.1.</span> <span class="toc-text">1. 核心功能概述</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-%E9%87%8D%E8%A6%81%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84"><span class="toc-number">1.2.</span> <span class="toc-text">2. 重要数据结构</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-%E5%85%B3%E9%94%AE%E5%87%BD%E6%95%B0"><span class="toc-number">1.3.</span> <span class="toc-text">3. 关键函数</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#loadHist-const-boost-filesystem-path-path-vfh-model-vfh"><span class="toc-number">1.3.1.</span> <span class="toc-text">loadHist(const boost::filesystem::path &amp;path, vfh_model &amp;vfh)</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#loadFeatureModels-const-boost-filesystem-path-base-dir-std-vector-models"><span class="toc-number">1.3.2.</span> <span class="toc-text">loadFeatureModels(const boost::filesystem::path &amp;base_dir, ... , std::vector&lt;vfh_model&gt; &amp;models)</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#main"><span class="toc-number">1.3.3.</span> <span class="toc-text">main(...)</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-%E7%94%9F%E6%88%90%E7%9A%84%E6%96%87%E4%BB%B6"><span class="toc-number">1.4.</span> <span class="toc-text">4. 生成的文件</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#5-%E6%B3%A8%E6%84%8F%E4%BA%8B%E9%A1%B9"><span class="toc-number">1.5.</span> <span class="toc-text">5. 注意事项</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BB%A3%E7%A0%81%E5%AE%9E%E7%8E%B0"><span class="toc-number">1.6.</span> <span class="toc-text">代码实现</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#nearest-neighbors-cpp-%E7%AC%94%E8%AE%B0"><span class="toc-number">2.</span> <span class="toc-text">nearest_neighbors.cpp 笔记</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-%E6%A0%B8%E5%BF%83%E5%8A%9F%E8%83%BD%E6%A6%82%E8%BF%B0-1"><span class="toc-number">2.1.</span> <span class="toc-text">1. 核心功能概述</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-%E9%87%8D%E8%A6%81%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84-1"><span class="toc-number">2.2.</span> <span class="toc-text">2. 重要数据结构</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-%E5%85%B3%E9%94%AE%E5%87%BD%E6%95%B0-1"><span class="toc-number">2.3.</span> <span class="toc-text">3. 关键函数</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#loadHist"><span class="toc-number">2.3.1.</span> <span class="toc-text">loadHist(...)</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#nearestKSearch"><span class="toc-number">2.3.2.</span> <span class="toc-text">nearestKSearch(...)</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#loadFileList"><span class="toc-number">2.3.3.</span> <span class="toc-text">loadFileList(...)</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#main-1"><span class="toc-number">2.3.4.</span> <span class="toc-text">main(...)</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-%E4%BF%AE%E5%A4%8D%E7%9A%84%E5%85%B3%E9%94%AE%E9%97%AE%E9%A2%98"><span class="toc-number">2.4.</span> <span class="toc-text">4. 修复的关键问题</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BB%A3%E7%A0%81%E5%AE%9E%E7%8E%B0-1"><span class="toc-number">2.5.</span> <span class="toc-text">代码实现</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2025/10/05/2025-10-05-lio_sam/" title="lio_sam">lio_sam</a><time datetime="2025-10-05T02:43:51.000Z" title="发表于 2025-10-05 10:43:51">2025-10-05</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2025/08/12/2025-08-12-%E4%BD%BF%E7%94%A8docker%E6%90%AD%E5%BB%BApytorch%E7%8E%AF%E5%A2%83/" title="使用docker搭建pytorch环境">使用docker搭建pytorch环境</a><time datetime="2025-08-12T12:43:33.000Z" title="发表于 2025-08-12 20:43:33">2025-08-12</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2025/08/05/2025-08-05-docker/" title="docker">docker</a><time datetime="2025-08-05T11:02:36.000Z" title="发表于 2025-08-05 19:02:36">2025-08-05</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2025/08/05/2025-08-05-%E8%BF%90%E5%8A%A8%E5%AF%B9%E8%B1%A1%E5%88%86%E5%89%B2%E4%B8%8E%E9%85%8D%E5%87%86%E7%AE%97%E6%B3%95/" title="运动对象分割与配准算法">运动对象分割与配准算法</a><time datetime="2025-08-05T08:16:02.000Z" title="发表于 2025-08-05 16:16:02">2025-08-05</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2025/08/05/2025-08-05-%E6%9D%A1%E4%BB%B6%E6%AC%A7%E5%BC%8F%E8%81%9A%E7%B1%BB%E5%88%86%E5%89%B2/" title="条件欧式聚类分割">条件欧式聚类分割</a><time datetime="2025-08-05T07:56:39.000Z" title="发表于 2025-08-05 15:56:39">2025-08-05</time></div></div></div></div></div></div></main><footer id="footer"><div class="footer-other"><div class="footer-copyright"><span class="copyright">&copy;&nbsp;2025 By Fi9zero</span><span class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo 7.3.0</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly 5.4.2</a></span></div><div class="footer_custom_text">Only light can attract bugs.</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="日间和夜间模式切换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside-config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><div class="js-pjax"><script>(() => {
  const loadMathjax = () => {
    if (!window.MathJax) {
      window.MathJax = {
        tex: {
          inlineMath: [['$', '$'], ['\\(', '\\)']],
          tags: 'none',
        },
        chtml: {
          scale: 1.1
        },
        options: {
          enableMenu: true,
          renderActions: {
            findScript: [10, doc => {
              for (const node of document.querySelectorAll('script[type^="math/tex"]')) {
                const display = !!node.type.match(/; *mode=display/)
                const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display)
                const text = document.createTextNode('')
                node.parentNode.replaceChild(text, node)
                math.start = {node: text, delim: '', n: 0}
                math.end = {node: text, delim: '', n: 0}
                doc.math.push(math)
              }
            }, '']
          }
        }
      }

      const script = document.createElement('script')
      script.src = 'https://cdn.jsdelivr.net/npm/mathjax/es5/tex-mml-chtml.min.js'
      script.id = 'MathJax-script'
      script.async = true
      document.head.appendChild(script)
    } else {
      MathJax.startup.document.state(0)
      MathJax.texReset()
      MathJax.typesetPromise()
    }
  }

  btf.addGlobalFn('encrypt', loadMathjax, 'mathjax')
  window.pjax ? loadMathjax() : window.addEventListener('load', loadMathjax)
})()</script><script>(() => {
  const runMermaid = ele => {
    window.loadMermaid = true
    const theme = document.documentElement.getAttribute('data-theme') === 'dark' ? 'dark' : 'default'

    ele.forEach((item, index) => {
      const mermaidSrc = item.firstElementChild
      const mermaidThemeConfig = `%%{init:{ 'theme':'${theme}'}}%%\n`
      const mermaidID = `mermaid-${index}`
      const mermaidDefinition = mermaidThemeConfig + mermaidSrc.textContent

      const renderFn = mermaid.render(mermaidID, mermaidDefinition)
      const renderMermaid = svg => {
        mermaidSrc.insertAdjacentHTML('afterend', svg)
      }

      // mermaid v9 and v10 compatibility
      typeof renderFn === 'string' ? renderMermaid(renderFn) : renderFn.then(({ svg }) => renderMermaid(svg))
    })
  }

  const codeToMermaid = () => {
    const codeMermaidEle = document.querySelectorAll('pre > code.mermaid')
    if (codeMermaidEle.length === 0) return

    codeMermaidEle.forEach(ele => {
      const preEle = document.createElement('pre')
      preEle.className = 'mermaid-src'
      preEle.hidden = true
      preEle.textContent = ele.textContent
      const newEle = document.createElement('div')
      newEle.className = 'mermaid-wrap'
      newEle.appendChild(preEle)
      ele.parentNode.replaceWith(newEle)
    })
  }

  const loadMermaid = () => {
    if (true) codeToMermaid()
    const $mermaid = document.querySelectorAll('#article-container .mermaid-wrap')
    if ($mermaid.length === 0) return

    const runMermaidFn = () => runMermaid($mermaid)
    btf.addGlobalFn('themeChange', runMermaidFn, 'mermaid')
    window.loadMermaid ? runMermaidFn() : btf.getScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(runMermaidFn)
  }

  btf.addGlobalFn('encrypt', loadMermaid, 'mermaid')
  window.pjax ? loadMermaid() : document.addEventListener('DOMContentLoaded', loadMermaid)
})()</script></div><script defer src="https://npm.elemecdn.com/jquery@latest/dist/jquery.min.js"></script><script defer data-pjax src="/js/pig.js"></script><script src="/js/weather.js"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="text-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="站内搜索..." type="text"/></div></div><hr/><div id="local-search-results"></div><div id="local-search-stats-wrap"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></div></body></html>